package org.yiming.tools.mqtt.client.client.command;

import lombok.extern.slf4j.Slf4j;
import org.yiming.tools.mqtt.client.ApplicationContext;
import org.yiming.tools.mqtt.client.client.MqttClient;

import java.util.Optional;
import java.util.regex.Pattern;

/**
 * @author renwenpeng
 * date  2022/3/25 4:54 下午
 */
@Slf4j
public class SubscribeCommand extends AbstractMqttCommand {

    private final String[] names = new String[]{"sub"};

    public SubscribeCommand(ApplicationContext applicationContext) {
        super(applicationContext);
    }

    @Override
    public String[] name() {
        return names;
    }

    @Override
    int argsMinLength() {
        return 1;
    }

    @Override
    String apply(MqttClient mqttClient, String[] args) {
        String topic = args[0];
        Optional<Integer> qosOptional = Optional
                .ofNullable(args.length > 1 && Pattern.matches("[0-2]", args[1]) ? Integer.parseInt(args[1]) : null);
        try {
            mqttClient.subscribe(topic, qosOptional.orElse(1));
            return String.format("Subscription [%s] succeeded", topic);
        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }

    @Override
    public String[] helpContent() {
        return new String[]{"sub", "{topic} ?{qos:1}"};
    }
}
